<?php
/**
 * 用户绑定卡片业务逻辑
 * User: Acer
 * Date: 2022/7/9
 * Time: 23:36
 */
namespace app\move\service;


use app\card\models\CardModel;
use app\card\models\CardProModel;
use app\move\models\CardUserModel;
use app\move\models\FamilyCardModel;
use app\move\models\IdentityCardModel;
use app\move\models\IdentityCardBlacklistModel;
use app\wx\models\UserModel;
use think\Cache;
use think\Loader;
use think\Log;

class CardUserService {
    // 验证手机号
    public function test_user_phone($phone,$uid){
        // 校验电话号码
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {  json_err(-210,['手机号码格式错误！']); exit();}
        // 判断当前该用户是否已绑定电话号码
        $IdUserInfo = (new IdentityCardModel())->where('uid',$uid)->find();
        $IdUserInfo = obj_to_arr($IdUserInfo);
        if(!empty($IdUserInfo['mobile']) && (int)$IdUserInfo['mobile'] !== (int)$phone) {  json_err(-210,['该电话号码与本人实名电话号码不符！']); exit();}

        // 获取号码信息
        $IdentityCardInfo = (new IdentityCardModel())->where('mobile',$phone)->find();
        $IdentityCardInfo = obj_to_arr($IdentityCardInfo);
        if(!$IdentityCardInfo) return 1; // 未存在电话号码信息
        // 是否本人操作
        if(!empty($IdentityCardInfo['uid']) && $IdentityCardInfo['uid'] !== $uid){  json_err(-210,['该手机号已被他人使用！']); exit();}

        // 判断用户手机号是否已实名
        $mobileUserInfo = (new IdentityCardModel())->where('uid',$uid)->where('mobile',$phone)->find();
        $mobileUserInfo = obj_to_arr($mobileUserInfo);
        if($mobileUserInfo) {  json_err(-211); exit();}
        return 2; // 存在电话号码，但是未绑定用户

    }
    // 发送验证码
    public function s_send_vcode($data){
        // 是否开启发送短信
        if((int)config('is_send_sms') !== 1){json_err(-210,['发送短信已关闭！']); exit();}
        // 查看当天发送次数是否已用完
        $this->is_send_news($data['phone']);
        // 校验电话号码
//        $res = $this->test_user_phone($data['phone'],$data['uid']);
        if(!preg_match("/^1[3456789]\d{9}$/", $data['phone'])) {  json_err(-210,['手机号码格式错误！']); exit();}
//        if($res){
        // 发送验证码
        $code = mt_rand(100000,999999);//自定义验证码
        $snd_news = $this->sendMsgPhone($data['phone'],$code);
        if($snd_news){
            // 查看是否记录发送次数
            $this->set_send_news($data['phone']);
            // 缓存当前用户、手机号和验证码
            $expire = 60 * 5; // 失效期为5分钟
            Cache::set($data['uid'].'_'.$data['phone'],$code,$expire);
            return true;
        }
//        }
        return false;
    }

    // 设置电话号码发送验证码限制
    public function set_send_news($phone){
        if(config('is_send_news') == 1){ // 开启限制
            $get_number=Cache::get($phone);
            $expire = 60 * 60 * 24; // 失效期为24h
            if(!$get_number){
                Cache::set($phone,1, $expire); // 失效期为24h
            }else{
                Cache::set($phone,(int)$get_number + 1, $expire); // 失效期为24h
            }
        }
    }

    // 电话号码发送验证码限制
    public function is_send_news($phone){
        // 获取当前验证码的发送次数，电话号码每天最多发送5条
        $send_phone_vcode_number=Cache::get($phone);
        if(!empty($send_phone_vcode_number) && (int)$send_phone_vcode_number >= config('send_phone_vcode_number') && config('is_send_news') == 1){
            json_err(-210,['发送次数已用完，24小时后再试！']);
        }
    }


    /**
     * 发送短信
     * @param $phone    电话号码
     * @param $code     验证码
     */
    public  function sendMsgPhone($phone,$code) {
        if(empty($phone)) json_err(-210,['电话号码，不能为空！']);
        if(empty($code)) json_err(-210,['验证码，不能为空！']);
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        import('aliyun-dysms-php-sdk.api_demo.SmsDemo',VENDOR_PATH,'.php');
        $SmsDemo = new \SmsDemo();
        $res = $SmsDemo->sendSms($phone,config('signName'),config('templateCode'),['code'=>$code]);
        if($res->Code == 'OK'){
            return obj_to_arr($res);
        }else{
            json_err(-210,[$res->Message]);
            exit();
        }
    }

    // 验证手机号码和验证码是否存在
    public function is_vocde_phone($phone,$uid,$code){
        $vcode =Cache::get($uid.'_'.$phone);
        if(!$vcode) json_err(-210,['验证码不存在！']);
        if((int)$vcode !== (int)$code) json_err(-210,['验证码错误！']);
        Cache::dec($uid.'_'.$phone); // 通过，清除验证码
        return true;
    }

    // 根据用户id，获取卡片绑定信息，且在有效期内
    public function user_card_info($uid,$is_active = 1){
        $CardUserModel = new CardUserModel();
        $CardUserModel->where('uid',$uid)->where('valid_time','<',time())->update(['is_active'=>2]); // 更改卡片状态
        return $CardUserModel->where([
            'is_active'=>$is_active,
            'uid'   =>  $uid,
        ])->find();
    }

    // 绑定手机号到指定用户
    public function user_bind_phone($data){
        // 验证码是否通过
        $this->is_vocde_phone($data['phone'],$data['uid'],$data['vcode']);
        // 判断手机号是否通行
        $res = $this->test_user_phone($data['phone'],$data['uid']);
        if($res == 2){
            (new IdentityCardModel())->where('mobile',$data['phone'])->update(['uid'=>$data['uid']]);
            return true;
        }else{
            $res = (new IdentityCardModel())->insert([
                'uid'       =>  $data['uid'],
                'mobile'    =>  $data['phone']
            ]);
            return $res;
        }
    }

    // 修改绑定手机号
    public function modify_bind_phone($data){
        // 验证码是否通过
        $this->is_vocde_phone($data['phone'],$data['uid'],$data['vcode']);

        // 获取号码信息
        $IdentityCardInfo = (new IdentityCardModel())->where('mobile',$data['phone'])->find();
        $IdentityCardInfo = obj_to_arr($IdentityCardInfo);
        if($IdentityCardInfo){  json_err(-210,['该手机号已被使用！']); exit();}

        (new IdentityCardModel())->where('uid',$data['uid'])->update(['mobile'=>$data['phone']]);
        return true;
    }

    // 判断当前是否存在卡片
    public function is_suer_bind_card($uid){
        $CardUserModel = new CardUserModel();
        $carderId  = $CardUserModel->where('uid',$uid)->value('pid');
        if($carderId) json_err(-210,['不能重复添加多张卡片！']);
        // 获取实名认证ID
        $WxUserService =new WxUserService();
        $user_did= $WxUserService->is_user_authentication(['uid'=>$uid]);
        if($user_did){
            $FamilyCardModel = new FamilyCardModel();
            $FamilyCard = $FamilyCardModel->where('did',$user_did)->find();
            $FamilyCard = obj_to_arr($FamilyCard);
            if($FamilyCard){
                if($FamilyCard['state']) json_err(-210,['您已是卡片成员，但卡片未激活！']);
                json_err(-210,['您已是卡片成员，不能重复添加多张卡片！']);
            }
        }
    }

//惠医接口對接
//加密
public static function aesEncrypt($str, $appSecret) {
    if (empty($str) || empty($appSecret)) {
        return null;
    }
    try {
        $cipher = "AES-128-ECB";
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $bytes = openssl_encrypt($str, $cipher, $appSecret, OPENSSL_RAW_DATA, $iv);
        return base64_encode($bytes);
    } catch (Exception $e) {
        throw new InvalidArgumentException("aes encrypt error", $e);
    }
}
//解密
public static function aesDecrypt($str, $appSecret) {
    if (empty($str) || empty($appSecret)) {
        return null;
    }
    try {
        $cipher = "AES-128-ECB";
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $str = base64_decode($str);
        $bytes = openssl_decrypt($str, $cipher, $appSecret, OPENSSL_RAW_DATA, $iv);
        return $bytes;
    } catch (Exception $e) {
        throw new InvalidArgumentException("aes decrypt error", $e);
    }
}

public function sendRequest($url, $str,$bizContent) {
    $appSecret = 'f172u75d812cea8be65d3e1513c6c0b9';
    $bizType = 'HTAllStar';
    $appId = 'esales';
    $timestamp = time();
    // 生成签名
    $str = $appId . $bizType . $str . $timestamp . $appSecret;
    $sign = md5($str);
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $bizContent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'bizType:'.$bizType,
        'appId:'.$appId,
        'timestamp:'.$timestamp,
        'sign:'. $sign
    ));
    $response = curl_exec($ch);

    curl_close($ch);


    return $response;
}

public function huiyi_active($hy_data){
        $bizContent = json_encode(array(
            "Uid" => $hy_data['uid'],
            "Username" =>$hy_data['username'],
            "IdentityNO" => $hy_data['did'],
            "UserMobilePhone" => $hy_data['mobile'],
            'CardID' => $hy_data['CardID'],
            'PassWord' => $hy_data['CardID'],
            'EffectiveYears' =>  $hy_data['EffectiveYears'],
    ));
    $appSecret = 'f172u75d812cea8be65d3e1513c6c0b9';
    // /加解密测试
    $encrypted = $this->aesEncrypt($bizContent,$appSecret);
    $back =  $this->aesDecrypt($encrypted,$appSecret);
    Log::record("=========加密==========".$encrypted);
    Log::record("=========解密==========".$back);

     $data =['bizContent' => $encrypted];
    // 发送加密后的数据
    $url = "http://m.huiyihealth.com/openapi/cart/activate";
   $huiyiRes= $this->sendRequest($url, $encrypted,json_encode($data));
    Log::record("=========惠医返回==========".$huiyiRes);

}


    // 激活卡片
     public function s_bind_active($data){
        // 是否开启了多卡模式
        if(config('single_card') !== 1){
            Log::record("多卡模式");
            $this->is_suer_bind_card($data['uid']);
        }
        // 激活码获取卡片信息
         $cardPro = (new CardProModel())->where('password',$data['card_code'])->find();
         $cardPro = obj_to_arr($cardPro);
         if(!$cardPro) {
             Log::record("卡片信息不存在");
             json_err(-204,['卡片信息，']);
         }
         // 判断卡片是否被激活
         $CardUserModel = new CardUserModel();
         $FamilyCardModel = new FamilyCardModel();
         $is_bind =  $CardUserModel->where(['pid'=> $cardPro['pid']])->find();
         if($is_bind) {
             Log::record("卡片已激活，不可重复绑定");
             json_err(-210,['卡片已激活，不可重复绑定！']);
         }
        // 该卡片状态是否可使用
        if( (int)$cardPro['state'] !== 1) {
            Log::record("卡片被禁用，不可激活");
            json_err(-210,['卡片被禁用，不可激活！']);
        }
        // 获取卡片配置
        $card_info =  (new CardModel())->where('cid',$cardPro['cid'])->find();
        if(!$card_info) {
            Log::record("卡片配置信息，不存在");
            json_err(-210,['卡片配置信息，不存在！']);
        }
        $card_info = obj_to_arr($card_info);

        // 获取当前卡片的有效期时间
        if($card_info['company'] == 1){ // 月
            $valid_date = date('Y-m-d H:i:s', strtotime('+'.$card_info['valid_number'].' months'));
            $time = strtotime($valid_date);
        }else if($card_info['company'] == 2){ // 年
            $valid_date = date('Y-m-d H:i:s', strtotime('+'.$card_info['valid_number'].' year'));
            $time = strtotime($valid_date);
        }else if($card_info['company'] == 3){ // 年
             $valid_date = date('Y-m-d H:i:s', strtotime('+'.$card_info['valid_number'].' days'));
             $time = strtotime($valid_date);
        }
            if($time <= time()){
                Log::record("卡片已经过期，不能激活");
                 json_err(-210,['卡片已经过期，不能激活！']);
            }

            // 激活有效期判断（金牌护理卡：出库判断，激活有效期判断）
            if(isset($cardPro['outbound'])&&$cardPro['outbound']==0){
                Log::record("卡片还未出库，不能激活");
                json_err(-210,['卡片还未出库，不能激活！']);
            }
            if(isset($card_info['active_validity_days'])&&$card_info['active_validity_days']>0){
		if(date("Y-m-d", time())>date("Y-m-d", strtotime('+'.$card_info['active_validity_days'].' days',strtotime($cardPro['outbound_time'])))){
                    Log::record('激活日超过'.$card_info['active_validity_days'].'天，不能激活！');
                    json_err(-210,['激活日超过'.$card_info['active_validity_days'].'天，不能激活！']);
                }
            }
            // 安护无忧卡
            if($card_info['ct_id']==17){
                // 此卡可叠加，最多可激活4张；激活第一张卡后需在30天内多张卡叠加完成，逾期不再叠加；等待期按第一张计算。（需要限制叠加最多4张+30天内叠加完成）
                $count = (new CardModel())->alias("c")->join('card_product cp', 'cp.cid=c.cid')
                    ->join('user_card uc', 'uc.pid=cp.pid')
                    ->where(['uc.uid'=>$data['uid'],'uc.is_other'=>$data['is_other'],'uc.is_active'=>1,'c.ct_id'=>17])->count();
                if($count>=4){
                    Log::record('最多可激活4张，已经激活'.$count.'张');
                    json_err(-210,['最多可激活4张']);
                }
            }

         // 激活卡片
            $installData =[
                'pid'            => $cardPro['pid'],//卡片id
                'uid'            => $data['uid'],
                'is_active'      =>  1,
                'valid_time'     =>  $time,
                'is_other'       =>  $data['is_other'],
                'policy_no'      => $data['policy_no'],
                'insurance_carriers' => $data['insurance_carriers']
            ];


            if(isset($data['manager_phone']) && !empty($data['manager_phone'])){
                $installData['manager_phone'] = $data['manager_phone'];
            }



         if(isset($data['equity_username'])){

            $CardUserModel->insertGetId($installData);
            //第一步写入家庭成员的身份信息入库,得到返回的身份id
            $IdentityCardModel = new IdentityCardModel();
            $idData =['id_card'=>$data['equity_idcard'],'name'=>$data['equity_username'],'mobile'=>$data['equity_mobile']];

            // 把难缠的客户的身份证放进黑名单，后续我们有其他新卡，这个身份证都激活不了，显示激活错误，请联系请联系工作人员
            if((new IdentityCardBlacklistModel())->where('id_card',$data['equity_idcard'])->count()>0){
                Log::record('激活错误，请联系请联系工作人员: '.$data['equity_idcard']);
                json_err(-210,['激活错误，请联系请联系工作人员']);
            }

            $did = $IdentityCardModel->insertGetId($idData);
            // $did = '1999';
            //激活家庭卡片
            $installData =[
                'pid'   => $cardPro['pid'],//卡片id
                'puid'  => $data['uid'], //上级用户id(根据上级的用户id，查找到卡片信息)',
                'did'   => $did,
                'state' => 1,
                'type'  => 999
            ];
            if($card_info['ct_id']==3){
                 $huiyi_data =[
                            'uid' =>$data['uid'],
                            'username' => $data['equity_username'],
                            'mobile' => $data['equity_mobile'],
                            'did'  => $data['equity_idcard'],
                            'CardID' => $cardPro['code'],
                            'PassWord' => $cardPro['password'],
                            'EffectiveYears' => $card_info['valid_number']
                         ];
                Log::record("发送惠医数据");
                $this->huiyi_active($huiyi_data);
            }
            Log::record("家庭卡保存数据");
            return    $FamilyCardModel->insertGetId($installData);

            }else{
                    $IdentityCardModel = new IdentityCardModel();
                  $ddata = $IdentityCardModel->where('uid',$data['uid'])->find();

             // 把难缠的客户的身份证放进黑名单，后续我们有其他新卡，这个身份证都激活不了，显示激活错误，请联系请联系工作人员
             if((new IdentityCardBlacklistModel())->where('id_card',$ddata['id_card'])->count()>0){
                 Log::record('激活错误，请联系请联系工作人员: '.$ddata['id_card']);
                 json_err(-210,['激活错误，请联系请联系工作人员']);
             }

             if($card_info['ct_id']==3) {
                 $huiyi_data = [
                     'uid' => $data['uid'],
                     'username' => $ddata['name'],
                     'mobile' => $ddata['mobile'],
                     'did' => $ddata['id_card'],
                     'CardID' => $cardPro['code'],
                     'PassWord' => $cardPro['password'],
                     'EffectiveYears' => $card_info['valid_number']
                 ];
                 Log::record("发送惠医数据");
                 $this->huiyi_active($huiyi_data);
             }

                Log::record("普通卡保存数据");
                return     $CardUserModel->insertGetId($installData);
            }
    }

    // 安护无忧卡叠加
    public function bind_active_append($data){
// 激活码获取卡片信息
        $cardPro = (new CardProModel())->where('password',$data['card_code'])->find();
        $cardPro = obj_to_arr($cardPro);
        if(!$cardPro) {
            Log::record("卡片信息不存在");
            json_err(-204,['卡片信息，']);
        }
        // 判断卡片是否被激活
        $CardUserModel = new CardUserModel();
        $is_bind =  $CardUserModel->where(['pid'=> $cardPro['pid']])->find();
        if($is_bind) {
            Log::record("卡片已激活，不可重复绑定");
            json_err(-210,['卡片已激活，不可重复绑定！']);
        }
        // 该卡片状态是否可使用
        if( (int)$cardPro['state'] !== 1) {
            Log::record("卡片被禁用，不可激活");
            json_err(-210,['卡片被禁用，不可激活！']);
        }
        // 获取卡片配置
        $card_info =  (new CardModel())->where('cid',$cardPro['cid'])->find();
        if(!$card_info) {
            Log::record("卡片配置信息，不存在");
            json_err(-210,['卡片配置信息，不存在！']);
        }
        $card_info = obj_to_arr($card_info);

        // 激活有效期判断（金牌护理卡：出库判断，激活有效期判断）
        if(isset($cardPro['outbound'])&&$cardPro['outbound']==0){
            Log::record("卡片还未出库，不能激活");
            json_err(-210,['卡片还未出库，不能激活！']);
        }
        if(isset($card_info['active_validity_days'])&&$card_info['active_validity_days']>0){
            if(date("Y-m-d", time())>date("Y-m-d", strtotime('+'.$card_info['active_validity_days'].' days',strtotime($cardPro['outbound_time'])))){
                Log::record('激活日超过'.$card_info['active_validity_days'].'天，不能激活！');
                json_err(-210,['激活日超过'.$card_info['active_validity_days'].'天，不能激活！']);
            }
        }
        $user_card = obj_to_arr((new CardUserModel())->where('cu_id', $data['cu_id'])->find());
        if(!$user_card){
            json_err(-210,['参数不正确，cu_id不存在！']);
        }
        // 安护无忧卡
        if($card_info['ct_id']==17){
            // 此卡可叠加，最多可激活4张；激活第一张卡后需在30天内多张卡叠加完成，逾期不再叠加；等待期按第一张计算。（需要限制叠加最多4张+30天内叠加完成）
            $count = (new CardUserModel())
                ->where('parent_cu_id', $data['cu_id'])
                ->whereOr('cu_id', $data['cu_id'])
                ->count();
            if($count>=4){
                Log::record('最多可激活4张，已经激活'.$count.'张');
                json_err(-210,['最多可激活4张']);
            }

            if($user_card && date("Y-m-d", time())> date("Y-m-d", strtotime('+30 days',strtotime($user_card['creation_time'])))){
                Log::record('需在30天内多张卡叠加完成: '.$user_card['creation_time']);
                json_err(-210,['需在30天内多张卡叠加完成']);
            }

            $time = $user_card['valid_time'];
            if($card_info['company'] == 1){ // 月
                $valid_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s', (int)$time).'+'.$card_info['valid_number'].' months'));
                $time = strtotime($valid_date);
            }else if($card_info['company'] == 2){ // 年
                $valid_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s', (int)$time).'+'.$card_info['valid_number'].' year'));
                $time = strtotime($valid_date);
            }else if($card_info['company'] == 3){ // 年
                $valid_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s', (int)$time).'+'.$card_info['valid_number'].' days'));
                $time = strtotime($valid_date);
            }
//            (new CardUserModel())->where('cu_id', $data['cu_id'])->update(['valid_time'=>$time]);

            // 获取当前卡片的有效期时间
//            if($card_info['company'] == 1){ // 月
//                $valid_date = date('Y-m-d H:i:s', strtotime('+'.$card_info['valid_number'].' months'));
//                $time = strtotime($valid_date);
//            }else if($card_info['company'] == 2){ // 年
//                $valid_date = date('Y-m-d H:i:s', strtotime('+'.$card_info['valid_number'].' year'));
//                $time = strtotime($valid_date);
//            }else if($card_info['company'] == 3){ // 年
//                $valid_date = date('Y-m-d H:i:s', strtotime('+'.$card_info['valid_number'].' days'));
//                $time = strtotime($valid_date);
//            }

//            $user_card['parent_cu_id'] = $data['cu_id'];

            // 代激活
            if($user_card['is_other']==1){
                $pid = $user_card['pid'];
                $uid = $user_card['uid'];
                $FamilyCard = $this->s_bind_agent_card_info($pid,$uid);
                if($FamilyCard){
                    $FamilyCardData = [
                        'pid'=>$cardPro['pid'],
                        'puid'=>$FamilyCard['puid'],
                        'did'=>$FamilyCard['did'],
                        'type'=>$FamilyCard['type'],
                        'state'=>$FamilyCard['state'],
                    ];
                    (new FamilyCardModel())->insertGetId($FamilyCardData);
                }
            }

            $user_card['valid_time'] = $time;
            $user_card['pid'] = $cardPro['pid'];
            $user_card['uid'] = $data['uid'];
            unset($user_card['cu_id']);
            unset($user_card['creation_time']);
            unset($user_card['update_time']);
            unset($user_card['parent_cu_id']);
            $cu_id = (new CardUserModel())->insertGetId($user_card);
            (new CardUserModel())
                ->where('cu_id',$data['cu_id'])
                ->whereOr('parent_cu_id',$data['cu_id'])->update(['parent_cu_id'=>$cu_id]);
            return $cu_id;
        }
    }

    // 年为单位
    public function year_time($number = 1){
        $interval = 1 * 24 * 3600;  // 一天
        $totalmonthday = $this->month_time($number *12);
        $year_time=  $interval * $totalmonthday * $number; // 年
        return $year_time;
    }
    // 月为单位
    public function month_time($number = 1){
        $dayTime = 1 * 24 * 3600;  // 一天
        // 当前时间距离下个月还有多少天
        $day = $this->less_day($number);
        var_dump('当前时间距离下个月还有多少天'.$day);
        // 一天 * 月天数
        $interval = $dayTime * $day;
        return $interval;
    }

    //当前时间距离指定月还有多少天
    public function less_day($month_number = 1)
    {
        $month_big = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
        //现在的月份
        $date_month_old = (int)date('m',time());
        //下个月的月份
        $date_month_new = $date_month_old + $month_number;

        //下个月1号的时间戳
        $date_time_new = strtotime('1 '.$month_big[$date_month_new-$month_number].' '.date('Y',time()));
        //今天的时间戳
        $date_time_old = strtotime(date('d',time()).' '.$month_big[$date_month_old-$month_number].' '.date('Y',time()));

        //距下月剩余时间
        $time_new = ($date_time_new - $date_time_old)/24/60/60- $month_number;
        return $time_new;
    }

    // 获取卡片绑定信息
    public function s_bind_card_info($pid,$uid){
        return (new CardUserModel())->where([
            'pid'   => $pid,
            'uid'   => $uid
        ])->find();
    }
   // 获取代激活卡信息
        public function s_bind_agent_card_info($pid,$puid){
            return (new FamilyCardModel())->where([
                'pid'   => $pid,
                'puid'   => $puid,
                'type' =>999,
                'state' =>  1
            ])->find();
        }
    // 获取家庭卡片绑定信息
    public function s_bind_family_card_info($pid,$did){
        return (new FamilyCardModel())->where([
            'pid'   => $pid,
            'did'   => $did,
            'state' =>  1
        ])->find();
    }
    // 获取卡片成员
    public function s_get_card_user_list($pid,$uid,$type = null){
        // 获取成员
        $FamilyCardModel = new FamilyCardModel();
        $IdentityCardModel = new IdentityCardModel();
        $whereData = [
            'pid'=>$pid,
            'puid'=>$uid
        ];
        if($type)$whereData['type'] = $type;
        $list = $FamilyCardModel->where($whereData)->select();
        // 获取成员信息
        $list = obj_to_arr($list);
        // 获取卡片成员时，0可以查本人
        if(isset($type) && $type == 0){
            $list = (new UserModel())->where(['id'=>$uid])->select();
            $list = obj_to_arr($list);
        }
        if(count($list) > 0){
            foreach($list as $key=>$value){
                // 获取用户信息
                $IdentityCar = $IdentityCardModel->where('did',$value['did'])->find();
                $list[$key]['user_info'] = (object)[];
                if($IdentityCar) $list[$key]['user_info'] = $IdentityCar;
            }
        }
        return $list;
    }

    // 激活卡片成员
    public function s_card_set($fid){
        $FamilyCardModel = new FamilyCardModel();
        $FamilyCardModel->where('fid','in',$fid)->update([
            'state' =>  1
        ]);
        return true;
    }
    // 获取用户明下所有的卡片
    public function s_get_user_card($uid){
        $CardUserModel = new CardUserModel();
        $list =  $CardUserModel->where('uid',$uid)->select();
        return obj_to_arr($list);
    }

    // 绑定保单号
    public function bind_policy_no($data){
        $value=['policy_no'=>'','insurance_carriers'=>''];
        if(isset($data['policy_no'])&&!empty($data['policy_no'])) $value['policy_no']=$data['policy_no'];
        if(isset($data['insurance_carriers'])&&!empty($data['insurance_carriers'])) $value['insurance_carriers']=$data['insurance_carriers'];
        (new CardUserModel())->where(['uid'=>$data['uid'],'cu_id'=>$data['cu_id']])->update($value);
        return true;
    }

}
